package com.dianrui.moonfire.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.SPUtils;
import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.alipay.PayResult;
import com.dianrui.moonfire.util.GlideUtil;
import com.dianrui.moonfire.util.MyUtil;
import com.dianrui.moonfire.util.NoDoubleClickUtils;
import com.dianrui.moonfire.okhttp.XHttpRequest;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.ToastUtil;
import com.dianrui.moonfire.util.Url;
import com.google.gson.JsonObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
/**
 * Description:违章记录详情
 * User: luoziyin
 * Date: 2020-8-17
 */
@SuppressWarnings("ALL")
public class ViolationDetailsActivity extends BaseActivity {
    private List<String> imgIdArray = new ArrayList<>();
    private String mViolationsId;
    private MainPageAdapter mainPageAdapter;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.mission_number)
    TextView missionNumber;
    @BindView(R.id.violation_type)
    TextView violationType;
    @BindView(R.id.violation_address)
    TextView violationAddress;
    @BindView(R.id.remarks)
    TextView remarks;
    @BindView(R.id.explain)
    TextView explains;
    @BindView(R.id.reply)
    TextView reply;
    @BindView(R.id.violation_money)
    TextView violationmoney;
    @BindView(R.id.click_illegal_handling)
    TextView clickIllegalhandling;//违章处理
    @BindView(R.id.click_fines)
    TextView clickFines;//缴纳罚款
    @BindView(R.id.image_pager)
    ViewPager imagePager;
    @BindView(R.id.check_order_details)
    TextView checkOrderDetails;
    @BindView(R.id.deteal_layout)
    LinearLayout detealLayout;
    @BindView(R.id.deteal_line)
    TextView detealLine;
    @BindView(R.id.reply_layout)
    LinearLayout replyLayout;
    @BindView(R.id.reply_line)
    TextView replyLine;


    @Override
    public int getContentViewId() {
        return R.layout.activity_violationdetails;
    }

    @Override
    public void initView() {
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle=getIntent().getExtras();
            if (bundle != null) {
                mViolationsId = bundle.getString("violation_id");
            }

        }
        customInit(true);
        title.setText(getString(R.string.violation_record_txt));

    }

    @Override
    protected void onResume() {
        super.onResume();
        getViolationsInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (imagePager != null) {
            imagePager.removeAllViews();
        }
    }

    @Override
    public void initData() {
    }

    private void getViolationsInfo() {
        JsonObject jsonObject = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        jsonObject.addProperty("violation_id", mViolationsId);
        XHttpRequest.getInstance().postRequests(Url.VIOLATIONINFO, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                if (imgIdArray != null && imgIdArray.size() > 0) {
                                    imgIdArray.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONObject("data").optJSONArray("picture");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        imgIdArray.add(jsonArray.optString(i));
                                    }
                                    if (mainPageAdapter == null) {
                                        mainPageAdapter = new MainPageAdapter();
                                        imagePager.setAdapter(mainPageAdapter);
                                    } else {
                                        mainPageAdapter.notifyDataSetChanged();
                                    }
                                }
                                showState(jsonObject);

                                missionNumber.setText(jsonObject.optJSONObject("data").optString("vehicle_number"));
                                violationType.setText(jsonObject.optJSONObject("data").optString("title"));
                                remarks.setText(jsonObject.optJSONObject("data").optString("remark"));
                                violationAddress.setText(jsonObject.optJSONObject("data").optString("address"));
                                violationmoney.setText(jsonObject.optJSONObject("data").optString("money"));
                                checkOrderDetails.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent=new Intent(ViolationDetailsActivity.this, OrderDetailActivity.class);
                                        Bundle bundle=new Bundle();
                                        bundle.putString("order_id", jsonObject.optJSONObject("data").optString("order_id"));
                                        intent.putExtras(bundle);
                                        startActivity(intent);
                                    }
                                });
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.net_error));

                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
    }

    //显示状态
    private void showState(JSONObject jsonObject) {
        int states = jsonObject.optJSONObject("data").optInt("state");
        // 状态:0未处理，1已处理(审核中)，2未通过，3已通过，4已撤销
        switch (states) {
            case 0:
                clickIllegalhandling.setVisibility(View.VISIBLE);
                clickFines.setVisibility(View.VISIBLE);
                detealLayout.setVisibility(View.GONE);
                detealLine.setVisibility(View.GONE);
                replyLayout.setVisibility(View.GONE);
                replyLine.setVisibility(View.GONE);
                break;

            case 1:
                clickIllegalhandling.setVisibility(View.VISIBLE);
                clickIllegalhandling.setEnabled(false);//不能点
                clickIllegalhandling.setText(getString(R.string.reviewing));
                clickIllegalhandling.setBackgroundColor(getResources().getColor(R.color.red1));
                clickIllegalhandling.setTextColor(getResources().getColor(R.color.white));
                clickFines.setVisibility(View.GONE);
                if ("1".equals(jsonObject.optJSONObject("data").optString("is_payment"))) {
                    explains.setText(getString(R.string.pay_penalty_txt));
                } else {
                    explains.setText(getString(R.string.violation_details_txt));
                }
                if (StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("reply"))) {
                    reply.setText(getString(R.string.no));
                } else {
                    reply.setText(jsonObject.optJSONObject("data").optString("reply"));
                }
                detealLayout.setVisibility(View.VISIBLE);
                detealLine.setVisibility(View.VISIBLE);
                replyLayout.setVisibility(View.VISIBLE);
                replyLine.setVisibility(View.VISIBLE);
                break;

            case 2:
                clickIllegalhandling.setVisibility(View.VISIBLE);
                clickFines.setVisibility(View.VISIBLE);
                if ("1".equals(jsonObject.optJSONObject("data").optString("is_payment"))) {
                    explains.setText(getString(R.string.pay_penalty_txt));
                } else {
                    explains.setText(getString(R.string.violation_details_txt));
                }

                if (StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("reply"))) {
                    reply.setText(getString(R.string.no));
                } else {
                    reply.setText(jsonObject.optJSONObject("data").optString("reply"));
                }
                detealLayout.setVisibility(View.VISIBLE);
                detealLine.setVisibility(View.VISIBLE);
                replyLayout.setVisibility(View.VISIBLE);
                replyLine.setVisibility(View.VISIBLE);
                break;

            case 3:
                clickIllegalhandling.setEnabled(false);//不能点
                clickIllegalhandling.setBackgroundColor(getResources().getColor(R.color.deep_blue));
                clickIllegalhandling.setTextColor(getResources().getColor(R.color.white));
                clickIllegalhandling.setText(getString(R.string.succed_pass));
                clickFines.setVisibility(View.GONE);
                if ("1".equals(jsonObject.optJSONObject("data").optString("is_payment"))) {
                    explains.setText(getString(R.string.pay_penalty_txt));
                } else {
                    explains.setText(getString(R.string.violation_details_txt));
                }

                if (StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("reply"))) {
                    reply.setText(getString(R.string.no));
                } else {
                    reply.setText(jsonObject.optJSONObject("data").optString("reply"));
                }
                detealLayout.setVisibility(View.VISIBLE);
                detealLine.setVisibility(View.VISIBLE);
                replyLayout.setVisibility(View.VISIBLE);
                replyLine.setVisibility(View.VISIBLE);
                break;
            case 4:
                clickIllegalhandling.setEnabled(false);//不能点
                clickFines.setEnabled(false);
                clickIllegalhandling.setBackgroundColor(getResources().getColor(R.color.grayness));
                clickIllegalhandling.setTextColor(getResources().getColor(R.color.white));
                clickIllegalhandling.setText(getString(R.string.undo));
                clickFines.setVisibility(View.GONE);
                if ("1".equals(jsonObject.optJSONObject("data").optString("is_payment"))) {
                    explains.setText(getString(R.string.pay_penalty_txt));
                } else {
                    explains.setText(getString(R.string.violation_details_txt));
                }

                if (StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("reply"))) {
                    reply.setText("无");
                } else {
                    reply.setText(jsonObject.optJSONObject("data").optString("reply"));
                }
                detealLayout.setVisibility(View.VISIBLE);
                detealLine.setVisibility(View.VISIBLE);
                replyLayout.setVisibility(View.VISIBLE);
                replyLine.setVisibility(View.VISIBLE);
                break;

            default:
                break;
        }
    }


    @OnClick({R.id.click_illegal_handling, R.id.click_fines, R.id.click_left, R.id.click_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.click_illegal_handling:
                Intent intent = new Intent(ViolationDetailsActivity.this, ViolationDealActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("violations_id", mViolationsId);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.click_fines:
                createPayDialog(violationmoney.getText().toString());
                break;
            case R.id.click_left:
                int currentItem = imagePager.getCurrentItem();
                imagePager.setCurrentItem(--currentItem);
                break;
            case R.id.click_right:
                int currentAddItem = imagePager.getCurrentItem();
                imagePager.setCurrentItem(++currentAddItem);
                break;

            default:
                break;
        }
    }


    //主页轮播适配器
    private class MainPageAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            if (imgIdArray == null) {
                return 0;
            }
            return imgIdArray.size();
        }

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return Objects.equals(view, object);
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, final int position) {
            ImageView imageView = new ImageView(ViolationDetailsActivity.this);
            if (imgIdArray.size() > 0) {//无论怎么样要判断集合，因为数据是从网络很有可能网络太差导致进界面就闪退
                GlideUtil.loadImageView(ViolationDetailsActivity.this, imgIdArray.get(position), imageView);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (imgIdArray != null && imgIdArray.size() > 0) {
                            List<String> temp = new ArrayList<>();
                            int picSizes = imgIdArray.size();
                            for (int i = 0; i < picSizes; i++) {
                                temp.add(imgIdArray.get(i));
                            }
                            startActivity(new Intent(ViolationDetailsActivity.this, BigImageActivity.class)
                                    .putStringArrayListExtra("data", (ArrayList<String>) temp).putExtra("current", position));
                        }
                    }
                });
            }
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }
    }

    @SuppressLint("InflateParams")
    private void createPayDialog(final String money) {
        final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(ViolationDetailsActivity.this);
        View view = LayoutInflater.from(ViolationDetailsActivity.this).inflate(R.layout.dialog_pays, null);
        Button pay = view.findViewById(R.id.pay);
        ImageView close = view.findViewById(R.id.close);
        LinearLayout clickZfb = view.findViewById(R.id.click_zfb);
        LinearLayout clickWx = view.findViewById(R.id.click_wx);
        final TextView showMoney = view.findViewById(R.id.show_dialog_money);
        final CheckBox cbZfb = view.findViewById(R.id.cb_zfb);
        final CheckBox cbWx = view.findViewById(R.id.cb_wx);
        String showMoneys = money;

        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(MyUtil.formatBy2Float(Float.parseFloat(money),2));
        showMoney.setText(stringBuilder.toString());

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomSheetDialog.dismiss();
            }
        });
        clickZfb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(true);
                cbWx.setChecked(false);
            }
        });
        clickWx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(false);
                cbWx.setChecked(true);
            }
        });
        cbZfb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(true);
                cbWx.setChecked(false);
            }
        });
        cbWx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(false);
                cbWx.setChecked(true);
            }
        });
        pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (cbWx.isChecked()) {
                    bottomSheetDialog.dismiss();
                    payWx(showMoney.getText().toString(), mViolationsId);
                } else if (cbZfb.isChecked()) {
                    bottomSheetDialog.dismiss();
                    paysZfb(showMoney.getText().toString(), mViolationsId);
                }
            }
        });
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.setCancelable(false );
        bottomSheetDialog.setCanceledOnTouchOutside(false);
        bottomSheetDialog.show();
    }


    private void payWx(String money, String violationId) {
        JsonObject payJson = new JsonObject();
        payJson.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        payJson.addProperty("payment_mode", "2");
        payJson.addProperty("money", money);
        payJson.addProperty("type", "4");
        payJson.addProperty("ids", violationId);
        XHttpRequest.getInstance().postRequests(Url.PAY, payJson.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.getString("status"))) {
                                IWXAPI msgApi = WXAPIFactory.createWXAPI(ViolationDetailsActivity.this, Constant.WXAppID, true);
                                if (!msgApi.isWXAppInstalled()) {
                                    ToastUtil.showToast("没有安装微信客户端");
                                }
                                PayReq payReq = new PayReq();
                                payReq.appId = jsonObject.optJSONObject("data").optString("appid");
                                payReq.partnerId = jsonObject.optJSONObject("data").optString("partnerid");
                                payReq.prepayId = jsonObject.optJSONObject("data").optString("prepayid");
                                payReq.packageValue = jsonObject.optJSONObject("data").optString("package");
                                payReq.nonceStr = jsonObject.optJSONObject("data").optString("noncestr");
                                payReq.timeStamp = jsonObject.optJSONObject("data").optString("timestamp");
                                payReq.extData = "violationPay";
                                payReq.sign = jsonObject.optJSONObject("data").optString("sign");
                                msgApi.sendReq(payReq);
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
    }


    private void paysZfb(String money, String violationId) {
        JsonObject payJson = new JsonObject();
        payJson.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        payJson.addProperty("payment_mode", "3");
        payJson.addProperty("money", money);
        payJson.addProperty("type", "4");
        payJson.addProperty("ids", violationId);
        XHttpRequest.getInstance().postRequests(Url.PAY, payJson.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.getString("status"))) {
                                if (!MyUtil.checkAliPayInstalled(ViolationDetailsActivity.this)) {
                                    ToastUtil.showToast(getString(R.string.zfb_installed));
                                    return;
                                }
                                Runnable payRunnable = new Runnable() {

                                    @Override
                                    public void run() {
                                        PayTask alipay = new PayTask(ViolationDetailsActivity.this);
                                        final Map<String, String> res = alipay.payV2(jsonObject.optJSONObject("data").optString("contents"), true);
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                PayResult payResult = new PayResult(res);
                                                String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                                                String resultStatus = payResult.getResultStatus();
                                                // 判断resultStatus 为9000则代表支付成功
                                                if ("9000".equals(resultStatus)) {
                                                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                                                    ToastUtil.showToast("支付成功");
                                                    finish();
                                                } else {
                                                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                                                    ToastUtil.showToast("支付失败");
                                                }
                                            }
                                        });
                                    }

                                };

                                Thread payThread = new Thread(payRunnable);
                                payThread.start();
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
    }

    @OnClick(R.id.back)
    public void onViewClicked() {
        finish();
    }


}
